import PureLogRoller from '../components/log-roller';
import * as LogAction from 'actions/log';
import * as React from 'react';
import * as ReactRedux from 'react-redux';

const mapStateToProps = (state, ownProps) => {
  return state.logs[ownProps.logKey] || {};
};

class LogRoller extends React.Component {
  componentDidMount() {
    const { url, logKey } = this.props;

    let offset = 0;

    const fetchLog = () => {
      this.props.dispatch(LogAction.getLog(logKey, url, offset))
        .then(({ error, payload }) => {
          if (!!error) {
            return;
          }
          const { status, nextOffset } = payload;
          if (status === 2) {
            return;
          }
          if (status === 1) {
            offset = nextOffset;
          }
          this.getLogTimeoutId = setTimeout(fetchLog, 3000);
        });
    };

    fetchLog();
  }

  componentWillUnmount() {
    if (this.getLogTimeoutId) {
      clearTimeout(this.getLogTimeoutId);
    }
    this.props.dispatch(LogAction.clearLog(this.props.logKey));
  }

  render() {
    const { content, status } = this.props;

    return <PureLogRoller content={content} rolling={status === 0 || status === 1}/>;
  }
}

export default ReactRedux.connect(mapStateToProps)(LogRoller);
